package com.czmh.etc.onlinepubsys.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.exceptions.ApiCodeException;
import org.apache.commons.codec.binary.Base64;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: AES 加解密工具类
 *
 */
@Slf4j
public class AESTools {

	private static final String ALGORITHM = "AES";
	private static final String CHARSET_UTF8="UTF-8";
	private static final int KEY_SIZE = 128;
	private static final int CACHE_SIZE = 1024;
	
	//参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值(16位字符串)
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey,String charset) throws Exception {
        try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(charset), "AES"));
			byte[] b = cipher.doFinal(content.getBytes(charset));
			// 采用base64算法进行转码,避免出现中文乱码
			return Base64.encodeBase64String(b);
		} catch (Exception e) {
			log.error("encrypt content:{},e:{}",content,e);
			throw new ApiCodeException(ApiCodeEnum.ERR_ENCRYPTION_FAILED);
		}
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串(16位字符串)
     * @param decryptKey 解密的key值
     * @param charset 字符编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey,String charset) throws Exception {
        try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
			cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(charset), "AES"));
			// 采用base64算法进行转码,避免出现中文乱码
			byte[] encryptBytes = Base64.decodeBase64(encryptStr);
			byte[] decryptBytes = cipher.doFinal(encryptBytes);
			return new String(decryptBytes);
		} catch (Exception e) {
			log.error("decrypt encryptStr:{},e:{}",encryptStr,e);
			throw new ApiCodeException(ApiCodeEnum.ERR_DECRYPT_FAILED);
		}
    }

	/**
	 * 加密文件
	 * 
	 * @param key             密钥(16位字符串)
	 * @param sourceFilePath  原文件路径
	 * @param encryptFilePath 加密文件路径
	 * @throws Exception
	 */
	public static void encryptFile(String key, String sourceFilePath, String encryptFilePath) throws Exception {
		File sourceFile = new File(sourceFilePath);
		File encryptFile = new File(encryptFilePath);

		if (!sourceFile.isFile()) {
			throw new Exception(sourceFilePath + " is not a file");
		}

		if (!sourceFile.exists()) {
			throw new Exception(sourceFilePath + " not exist");
		}

		if (!encryptFile.getParentFile().exists()) {
			encryptFile.getParentFile().mkdirs();
		}

		encryptFile.createNewFile();
		InputStream inputStream = new FileInputStream(sourceFile);
		OutputStream outputStream = new FileOutputStream(encryptFile);
		Key k = new SecretKeySpec(Base64.decodeBase64(key), ALGORITHM);
		byte[] raw = k.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
		byte[] cache = new byte[CACHE_SIZE];
		int read = 0;
		while ((read = cipherInputStream.read(cache, 0, cache.length)) != -1) {
			outputStream.write(cache, 0, read);
		}
		outputStream.close();
		cipherInputStream.close();
		inputStream.close();
	}

	/**
	 * 解密文件
	 * 
	 * @param key             密钥
	 * @param encryptFilePath 加密文件路径
	 * @param targetFilePath  目标文件路径
	 * @throws Exception
	 */
	public static void decryptFile(String key, String encryptFilePath, String targetFilePath) throws Exception {
		File encryptFile = new File(encryptFilePath);
		File targetFile = new File(targetFilePath);

		if (!encryptFile.isFile()) {
			throw new Exception(encryptFilePath + " is not a file");
		}

		if (!encryptFile.exists()) {
			throw new Exception(encryptFilePath + " not exist");
		}

		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}

		targetFile.createNewFile();
		InputStream inputStream = new FileInputStream(encryptFile);
		OutputStream outputStream = new FileOutputStream(targetFile);
		Key k = new SecretKeySpec(Base64.decodeBase64(key), ALGORITHM);
		byte[] raw = k.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
		byte[] cache = new byte[CACHE_SIZE];
		int read = 0;
		while ((read = inputStream.read(cache, 0, cache.length)) != -1) {
			cipherOutputStream.write(cache, 0, read);
		}
		outputStream.close();
		cipherOutputStream.close();
		inputStream.close();
	}

	
	public static void main(String[] args) throws Exception {
		System.out.println(encrypt("0", "ABCDEFG123456789", "UTF-8"));
		Map<String, Object> map = new HashMap<>();
		map.put("time", Date.from(Instant.now()).getTime());
//		map.put("clientKey", "15089455982");
//		map.put("tel", "15089455982");
//		map.put("password", "admin123");
//		map.put("tokenId", "admin123");
		//修改图像
//		map.put("clientKey", "15089455982");
//		map.put("srcUser", "93351821178096312982813557352348");
//		map.put("tokenId", "006hze07txj7qw7mje9j213557352348");
		//发送短信
		map.put("clientKey", "15089455985");
		map.put("tel", "15089455985");
		map.put("types", "1");
		map.put("tokenId", "a393u22ucobhybetmpnag15089455982");
		//注册
//		map.put("clientKey", "15089455982");
//		map.put("tel", "15089455982");
//		map.put("types", "1");
//		map.put("password", "admin123");
//		map.put("securityCode", "592357");
//		map.put("versionNo", "20200701175211");
		
		//2.1.5	校验个人信息接口
//		map.put("clientKey", "15089455982");
//		map.put("tel", "15089455984");
//		map.put("types", "1");
//		map.put("password", "admin123");
//		map.put("securityCode", "013376");
//		map.put("versionNo", "20200630150204");
		
		//2.1.5	绑卡
//		map.put("clientKey", "15089455982");
//		map.put("tel", "15089455982");
//		map.put("srcUser", "wkpnml6ukolfxdfpdpz8b15089455982");
//		map.put("cardNo", "1611220102015842");
//		map.put("securityCode", "758195");
//		map.put("versionNo", "20200702094453");
//		map.put("tokenId", "a393u22ucobhybetmpnag15089455982");
		
		//2.1.5	查询卡列表
//		map.put("clientKey", "15089455982");
//		map.put("srcUser", "wkpnml6ukolfxdfpdpz8b15089455982");
//		map.put("tokenId", "a393u22ucobhybetmpnag15089455982");
		
//		//充值到账
//		map.put("clientKey", "FE3B3E3A-D17E-41A4-9286-FE65D780B499");
//		map.put("srcUser", "93351821178096312982813557352348");
//		map.put("tokenId", "006hze07txj7qw7mje9j213557352348");
//		map.put("orderNo", "CZDD2020072120000011");
//		String json = JSONUtil.toJsonStr(map);
//		System.out.println(json);
//		System.out.println(encrypt(json, "ABCDEFG987654321", "UTF-8"));
//		String resp =  "{\r\n" +
//				"  \"code\" : \"200\",\r\n" +
//				"  \"msg\" : \"成功\",\r\n" +
//				"  \"bizContent\" : {\r\n" +
//				"    \"name\" : \"\",\r\n" +
//				"    \"word\" : \"Hi , from com.hgsoft.rpc.server.demo.DemoServiceImpl as 1591964019851\"\r\n" +
//				"  }\r\n" +
//				"}";
//
//		ApiRespDto apiRespDto = ObjectMapperUtils.json2Object(resp, ApiRespDto.class);
//		System.out.println(resp);
//		
//		String s="pn9AiHcl+arVu/UUcuy7uD6DaypNqIAVUWbAMczti0PqzsUSAVj2oe+sWYrD6Z99FRsHiW04NxjNWPM+2IVV1COKkjaiyZ+cSfOgGTOdqLiwXN9NMFfC4EXMTTQuj7U2lxH/1yk7TU/qLsZwopIdK+I94NNa8r5Zs+BIZkvgI5s+Tr0g5nl16U3VM2Q91xbBKte2tXv1cEzKAmeMGThRwNAJ1uk4h8JUT8I8uSzc4Fo=";
//		System.out.println(decrypt(s, "ABCDEFG987654321", "utf-8"));
		
//		HttpResponse response = HttpRequest.post("http://10.173.235.128:8799/api/user/upload")
//				  .form("bizContent", "PHZNSYxTTnOAlOK1+SCcHhUUQ9hHeGh+4ISr/gBbEvpHhdJsHStH0Oujho1RyEPNhFQ3BNw8LlO70OUQiSYCaTjLelpxFwCqR6r8htaNJq+6IJ66FxiGJ3fVyocgaxWoi4cK03qqLFpBdXYsGifGSmV9pXgDtozaQQNRyKpHU0LQxFQiuuntiRo31wV8KJWPbvWgxtBs1q7xWMEFfOCpYGz+d2kM2wlFHIX6YObz9Jo=")
//				  .form("accessNo", "123456")
//				  .form("encryptType", "AES")
//				  .form("format", "UTF-8")
//				  .form("timestamp", "1")
//				  .form("version", "1000")
////				  .form("image", "1000")
//				  .form("image", new File("C:/Users/Administrator/Pictures/20200611170209938.jpg"))
//				  .form("charset", "UTF-8").execute();
//		String result2 = response.body();
//		System.out.println(result2);
	}
	
}
